package models

import (
	"fmt"
	"gin-easy/pkg/viper_config"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

var db *gorm.DB

func Setup() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		viper_config.Conf.Mysql.User,
		viper_config.Conf.Mysql.Pwd,
		viper_config.Conf.Mysql.Host,
		viper_config.Conf.Mysql.Port,
		viper_config.Conf.Mysql.DateBase)
	sql, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("数据库链接错误")
	}
	if viper_config.Conf.Mysql.Migrate {
		sql.AutoMigrate(&User{}, &Article{})
	}
	db = sql
}
